// mircoApp/videoOnDemand/index/index.js
// pages/member/course/CourseDetail/CourseDetail.js
import Dialog from "../../../dist/dialog/dialog";
import polyvLive from "../../../utils/polyvlive.js";
var CryptoJS = require("../../../utils/CryptoJS.js");
var yz_pay = require('../../../mycomponent/yz_pay/yz_pay');
var app = getApp();
Page({
  behaviors: [yz_pay],

  /**
   * 页面的初始数据
   */
  data: {
    course_name:"",
    duration_log_flag:true,
    relation_order_id:"",
    flag:true,
    current_time:1,
    current_min:1,
    timer_study:null,
    imgPath: app.globalData.imgPath,
    is_try:0,
    watch_type:0,
    buy_course:1,

    total_page: 1,
    page: 1,
    video_courses: [],

    has_many_dig_chapter_nums: 0,
    has_many_chapter_nums: 0,
    is_favorite: 0,
    showSahre: false,
    popupModeshow: false,
    navList: [
      // {
      //   id: "list0",
      //   name: "课程目录"
      // },
      // {
      //   id: "list1",
      //   name: "课程简介"
      // },
      // {
      //   id: "list2",
      //   name: "评论"
      // }
    ],

    navIdx: 0,
    anchorArray: null,

    is_try_time: null,
    is_questionnaire_time: null,
    // 问卷调查
    questionnaire_is_open: false,
    language: "",
    goods_id: "",
    is_show: true,
    is_vshow: false,
    isVideo: true,
    isLook: true,
    is_update: false,
    is_buy: false,
    showPopup: false,
    rewardMoneyBtn: false,
    actionSheetShow: false,
    rewardBtnShow: false,
    // 打赏金额
    rewardMoney: "",
    goodTit: "",
    goodPrice: "",
    chapterNum: "",
    teacherImg: "",
    teacherName: "",
    goodsContent: "",
    chapterList: [],
    article_content: "",
    courseShare: {},
    courseData: {},
    codeUrl: "",
    vedioSrc: "",
    coverImg: "",
    active: 1,
    // 章节id
    chapter_id: "",
    // 课程id
    courseId: "",
    pushGoodList: [],
    actionSheetItems: [],
    activeNames: 1,
    //章节列表
    chapterdigList: [],
    // 价格权限
    vip_level_status: {},
    islive: false,
    video_err: false,
    is_playLive: false,
    live: false,
    // islive:false,
    ios_virtual_pay: false,

    point_goods: "",
    integral: "积分",
    show1: false,

    posterShow: false,
    styleSetOptions: {}, //后台基础设置-样式设置
    countDownTime: null,
    timeData: {},
    iscCountDownFinish: false, //课程有效期是否到了
    HasBuyPermissions: false, //是否有购买权限，true则不可以下单

    videoEventDom:null,
    viewingDuration: 0, //已观看时长
    active_tab: 0,
    goods_plugin: null,
    iPnoneBottomBol:false,

    goodsInfo:{},
    //新加的参数
    speedShow:false,
    timingTime:1,
    speedActions:[
      // { text: '0.25x', val: 0.25 },
      { text: '0.5x', val: 0.5 },
      { text: '0.8x', val: 0.8 },
      { text: '倍速', val: 1 },
      { text: '1.25x', val: 1.25 },
      { text: '1.5x', val: 1.5 },
      // { text: '1.75x', val: 1.75 },
      { text: '2x', val: 2 }
    ],
    pictureMode: [],
    hoverPlay:false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(options, "====")
    this.setData({
      active:options.chapter_id,
      chapter_id: options.chapter_id,
      courseId: options.courseId,
      goods_id: options.goods_id,
      activeNames:(options.index -1)||0
    })
    this._getData();
  },
  getiPnoneBottom() {
    let value = wx.getStorageSync("iPhoneBottom");
    if (value) {
      this.setData({
        iPnoneBottomBol: true,
      });
    }
  },
  speedOn() {
    this.setData({
      speedShow:true
    })
  },
  speedOnClose() {
    this.setData({
      speedShow:false
    })
  },
  speedConfirm(event) {
    let detail = event.detail;
    this.data.videoEventDom.playbackRate(detail.value.val);
    this.setData({
      speedShow:false
    })
  },
  setShare() {
    this.setData({
      showSahre: !this.data.showSahre
    });
  },
  change_tab(e) {
    this.setData({
      active_tab: e.detail.index
    })
  },
  handleContact(e) {
    let _url = e.currentTarget.dataset.url;
    if (_url) {
      wx.navigateTo({
        url: _url,
        fail: function (err) {
          app.tips('客服路径错误');
        }
      });
    }
  },
  tapkefu() {
    this.setData({
      show1: true,
    });
  },
  callPhone() {
    wx.makePhoneCall({
      phoneNumber: this.data.service_mobile,
    });
  },
  closePop() {
    this.setData({
      show1: false,
    });
  },
  changeLoading() {
    wx.showLoading({
      title: '视频缓存中...',
    });
  },
  seekcomplete(){
    console.log('缓存完毕');
    wx.hideLoading();
  },
  setPosterShow() {
    this.setData({
      posterShow: !this.data.posterShow
    });
  },
  videoErr() {
    wx.hideLoading()
    wx.showToast({
      title: "视频加载出错了！",
      icon: "none",
      duration: 2000,
    });
  },
  loadedmetadata(){
    console.log('视频触发触发');
    wx.hideLoading()
  },
  getQrCode() {
    var that = this;
    app._getNetWork({
      url: app.getNetAddresss("member.member.getArticleQr"),
      success: function (res) {
        if (res.data.result == 1 && !app._isTextEmpty(res.data.data)) {
          let _data = res.data.data;
          that.setData({
            codeUrl: _data,
          });
        } else {
          console.error(res);
        }
      },
      fail: function (res) {
        console.error(res);
      },
    });
  },
  secret(string, code, operation) {
    code = CryptoJS.MD5(code).toString();
    var iv = CryptoJS.enc.Utf8.parse(code.substring(0, 16));
    var key = CryptoJS.enc.Utf8.parse(code.substring(16));
    if (operation) {
      return CryptoJS.AES.decrypt(string, key, {
        iv: iv,
        padding: CryptoJS.pad.Pkcs7
      }).toString(CryptoJS.enc.Utf8);
    }
    return CryptoJS.AES.encrypt(string, key, {
      iv: iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7
    }).toString();
  },
  // 点击直播请求
  addzhibo() {
    var that = this;
    app._getNetWork({
      url: app.getNetAddresss("plugin.video-demand.api.video-course-goods.get-live-info"),
      data: {
        goods_id: that.data.goods_id,
      },
      success: function (res) {
        if (res.data.result == 1) {
          if (that.data.islive == true) {
            wx.showToast({
              title: "正在直播",
              icon: "none",
              duration: 1000,
            });
            return;
          }
          let info = JSON.parse(that.secret(res.data.data, "zoQUA@257ggflNmMppKzcU7QgYyp!tU&h54VNN3u!PAU$8FxBW", true));
          that.is_onlive(info.userId, info.channelId);
          that.setData({
            islive: true,
          });
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: "none",
            duration: 1000,
          });
          that.setData({
            is_update: true,
            is_buy: true,
          });
        }
      },
      fail: function (res) {
        console.error(res);
      },
    });
  },
  // 唤起直播
  is_onlive(liveUid, liveVid) {
    wx.showLoading({
      title: "加载直播中",
      icon: "none",
    });
    const liveVideoContext = wx.createLivePlayerContext("polyvLiveVideo");
    this.setData({
      islive: true,
    });
    polyvLive.getVideo({
      uid: liveUid,
      vid: liveVid,
      videoContext: liveVideoContext,
      success: (videoInfo) => {
        // set video src and poster
        this.setPlayerSrc(videoInfo);
      },
      error: (res) => {
        console.log(res.error);
      },
      onStartLive: () => {
        console.log("start live");
        wx.hideLoading();
        // set latest video src
        this.setNewPlayerSrc();
      },
      onApiStatus: (status) => {
        console.log(status);
        if (status == "end") {
          this.setData({
            is_playLive: false,
            islive: false,
            is_vshow: true,
          });
          wx.hideLoading();
          wx.showToast({
            title: "当前无直播",
            icon: "none",
            duration: 1000,
          });
          polyvLive.destroy();
        } else if (status == "live") {
          this.setData({
            is_playLive: true,
          });
        }
      },
    });
  },
  // 直播赋值
  setPlayerSrc(videoInfo) {
    this.setData({
      video: {
        src: videoInfo.src, // 如果播放组件为video,只能用videoInfo.src(m3u8地址)，如果为live-player则用videoInfo.flvSrc
        poster: videoInfo.poster,
      },
      is_bisrc: videoInfo.src,
    });
  },
  setNewPlayerSrc() {
    polyvLive.getNewVideo((videoInfo) => {
      this.setPlayerSrc(videoInfo);
    });
  },

  goSurvey() {
    wx.navigateTo({
      url: "/packageE/questionnaire/questions/questions?goods_id=" + this.data.goods_id + "&tag=video",
    });
  },
  _getData() {
    // 初次获取数据
    app._getNetWork({
      url: app.getNetAddresss("plugin.video-demand.api.video-course-goods.get-course-goods-detail"),
      data: {
        goods_id: this.data.goods_id,
      },
      success: (res)=> {
        if (res.data.result === 1) {
          let _data = res.data.data;


          if (app._isTextEmpty(_data.has_many_dig_chapter) || _data.has_many_dig_chapter.length == 0) {
            Dialog.alert({
              title: "提示",
              message: `${_data.lang.course_name}已下架！`,
              context: this,
            }).then(() => {
              // on close
              wx.navigateBack({
                delta: 1,
              });
            });
            return;
          } else {
            this.setData({
              chapterdigList: _data.has_many_dig_chapter,
            });
          }

          _data.has_one_goods.content = _data.has_one_goods.content.replace(/<img/gi, '<img style="max-width:100%;height:auto;display:block" ');

          let playCourse = "";
          let playActive = 0;
          let has_many_dig_chapter = _data.has_many_dig_chapter;
          this.data.relation_order_id = _data.relation_order_id;

          for (let j = 0; j < has_many_dig_chapter.length; j++) {
            if (has_many_dig_chapter[j].has_many_chapter.length > 0 && this.data.chapter_id) {
              for (let i = 0; i < has_many_dig_chapter[j].has_many_chapter.length; i++) {
                if (has_many_dig_chapter[j].has_many_chapter[i].id === Number(this.data.chapter_id)) {
                  playCourse = has_many_dig_chapter[j].has_many_chapter[i];
                  playActive = i;
                }
              }
            } else {
              playActive = 0;
              playCourse = has_many_dig_chapter[0].has_many_chapter[0];
            }
          }

          let goodPrice = "";
          if (this.data.point_goods) {
            goodPrice = this.data.point_goods.point;
          } else {
            goodPrice = _data.has_one_goods.price;
          }
          let countDownTime = _data.course_expiration_time ? app.getTimeDifference(_data.course_expiration_time) : null;
          if(goodPrice == '0.00'){
            this.setData({buy_course:1})
          }else{
            this.setData({buy_course:_data.is_buy,is_try:_data.is_try})
          }
          wx.setNavigationBarTitle({
            title: `${_data.lang.course_name}目录`,
          })
          this.setData({
            course_name:_data.lang.course_name,
            goodsInfo:_data,
            course_id: _data.id,
            has_many_dig_chapter_nums: _data.has_many_dig_chapter.length,
            has_many_chapter_nums: _data.course_chapter_num,
            courseData: _data,
            rewardBtnShow: _data.is_reward,
            goodTit: _data.has_one_goods.title,
            goodPrice: goodPrice,
            vip_level_status: _data.has_one_goods.vip_level_status,
            chapterNum: _data.course_chapter_num,
            teacherImg: _data.has_one_lecturer && _data.has_one_lecturer.has_one_member ? _data.has_one_lecturer.has_one_member.avatar : '',
            teacherName: _data.has_one_lecturer && _data.has_one_lecturer.real_name || '',
            goodsContent: _data.has_one_goods.content,
            chapter_id: playCourse && playCourse.id || 0,
            isLook: playCourse && playCourse.is_audition || true,
            courseId: _data.id,
            pushGoodList: _data.pushGoods,
            courseShare: _data.has_one_goods.has_one_share,
            live: _data.live,
            live_title: _data.live_title,
            questionnaire_time: _data.questionnaire_time,
            service_QRcode: _data.shopSet.service_QRcode,
            service_mobile: _data.shopSet.service_mobile,
            shopSet: _data.shopSet,
            plugin_point_name: _data.plugin_point_name ? _data.plugin_point_name : '',
            styleSetOptions: _data.styleSet,
            countDownTime: countDownTime,
            HasBuyPermissions: _data.buyPermissions || false,
            advertising: _data?.has_one_goods?.has_one_goods_advertising ?? {},
            goods_plugin: _data.plugin,
            navList:[{id:"list0",name:`${_data.lang.course_name}目录`},{id:"list1",name:`${_data.lang.course_name}简介`},{id:"list2",name:'评论'}]
          });

          this.getVideoCourse();
          let sec = _data.questionnaire_time * 1000;
          if (_data.questionnaire_is_open) {
            if (this.data.is_opens == "close") {
              console.log(this.data.is_opens);
            } else {
              this.data.is_questionnaire_time = setTimeout(() => {
                if (!this.data.is_questionnaire_time) {
                  return;
                }
                this.setData({
                  questionnaire_is_open: _data.questionnaire_is_open,
                });
              }, sec);
            }
          }

          
          
          switch (_data.watch) {
            case 0:
              // Dialog.alert({
              //   title: '提示',
              //   message: '请升级会员或者购买课程',
              //   context: this
              // }).then(() => {
              //   // on close
              // })
              this.setData({
                is_update: false,
                is_buy: false,
              });
              this.videoInit(playActive, playCourse);
              break;
            case 1:
              // 判断是否免费章节
              // if (playCourse.is_audition == 1) {
              this.setData({
                is_update: false,
                is_buy: false,
                is_show: false,
                is_vshow: true,
              });
              this.videoInit(playActive, playCourse);
              break;
              // } else if (playCourse.is_audition == 0) {
              //   Dialog.alert({
              //     title: "提示",
              //     message: "请升级会员或者购买课程",
              //     context: this,
              //   }).then(() => {
              //     // on close
              //   });
              //   this.setData({
              //     is_update: true,
              //     is_buy: true,
              //   });
              //   break;
              // } else {
              //   break;
              // }
            case 2:
              this.setData({
                is_update: false,
                is_buy: false,
              });
              this.videoInit(playActive, playCourse);
              break;
            case 3:
            case 4:
              this.setData({
                is_update: false,
                is_buy: false,
              });
              this.videoInit(playActive, playCourse);
              break;
            default:
              break;
          }

          wx.setStorageSync("orderErrReturnUrl", _data.mini_not_permit_link); //无权限购买时，下单弹出框确认按钮跳转路径
        } else {
          wx.showToast({
            title: "视频加载出错",
            icon: "none",
            duration: 1500,
          });
          console.error(res);
        }
      },
      fail: function (res) {
        console.error(res);
      },
    });
  },
  videoInit(index, item) {
    // if(!item) return;
    this.setData({
      is_show: false,
      is_vshow: true,
      active: item.id,
    });
    this.viewPermission(item.id, index, item.course_id, item.is_audition);
    this.isMp4(this.data.vedioSrc);
  },
  viewPermissionBtn(e) {
    let dataset = e.currentTarget.dataset;
    let id = dataset.item.id;
    let index = dataset.index;
    let course_id = dataset.item.course_id;
    let audition = dataset.item.is_audition;
    this.setData({ //点击视频清空背景图片，不然升级会员切换免费观看，会出现上一张的背景图片
      coverImg:''
    }); 
    if(audition==0&&this.data.buy_course==0&&this.data.is_try==0){

      this.setData({ is_vshow:false,is_show:true,watch_type:0,active:id,isLook:false,coverImg:this.data.goodsInfo.has_one_goods.thumb})
      this.openBuyDialog();
      return;
    };
    this.viewPermission(id, index, course_id, audition);
  },
  back(){
    let pages = getCurrentPages();
    let prevpage = pages[pages.length - 2]; //上一个页面对象
    if(prevpage.route == 'packageA/detail_v2/detail_v2') {
      wx.navigateBack();
    } else {
      wx.navigateTo({
        url: `/packageA/detail_v2/detail_v2?id=${this.data.goods_id}`,
      });
    }
    // wx.navigateBack();
  },
  // 根据观看权限
  viewPermission(id, index, course_id, audition) {
    // id, index, address, course_id, audition
    let that = this;
    this.setData({
      is_show: false,
      is_vshow: true,
      islive: false,
    });
    this.setData({
      chapter_id: id,
      active: id,
    });

    let param = {
      goods_id: this.data.goods_id,
      chapter_id: id,
    };
    let url = app.getNetAddresss("plugin.video-demand.api.video-course-goods.get-video-address");
    app._getNetWork({
      url: url,
      data: param,
      success: function (res) {
        if (res.data.result == 1) {
          let _data = res.data.data;
          that.viewType(_data.watch, index, _data.video_address, course_id, id, audition, _data.video_cover_address, _data.is_try, _data.try_time,_data.hover_play);
          
        } else {
          console.error(res);
        }
      },
      fail: function (res) {
        console.error(res);
      },
    });
  },
  viewType(type, index, address, course_id, id, audition, coverSrc, is_try, try_time,hover_play) {
    console.log(this.data.is_show,"==2222");
    this.setData({watch_type:type})
    this.freeTime = -1;
     //是否开启悬浮播放 
     hover_play?this.data.pictureMode = ['push', 'pop']:this.data.pictureMode = []
     this.setData({
       pictureMode:this.data.pictureMode,
       hoverPlay:hover_play
     })
    if (is_try == 1 && type == 1 && audition == 1) {
      this.setData({
        coverImg: coverSrc,
        is_update: false,
        is_buy: false,
        isLook: true,
        is_vshow: true,
        is_show: false,
      });
      this.videoPlay(index, address, course_id, id, coverSrc);

      this.getHistory(course_id,id); //试看状态不执行记忆播放
      return;
    } else if (type != 2 && type != 3 && type != 4 && is_try == 1 && try_time > 0) {
      this.setData({
        is_update: false,
        is_buy: false,
        isLook: true,
      });
      this.freeTime = try_time;
      console.log('走试看的逻辑');
      console.log(this.data.videoEventDom);
      setTimeout(() => { //不设置定时器，无法自动播放
        if(!this.data.videoEventDom) {
          this.data.videoEventDom = wx.createVideoContext('polyvLiveVideo', this);
          this.data.videoEventDom.seek(0);
          this.data.videoEventDom.play();
        } else {
          this.data.videoEventDom.seek(0);
          this.data.videoEventDom.play();
        }
      },1000)
      this.videoPlay(index, address, course_id, id, coverSrc);
      return;
    } else {
      this.setData({
        vedioSrc: address,
        coverImg: coverSrc,
      });
     
      this.isMp4(this.data.vedioSrc);
    }
    console.log(this.data.is_show,"is_show==");
    this.data.flag = true;
   
    switch (type) {
      case 0:
        this.setData({
          // is_vshow: false,
          // is_show: true,
          is_show:false,
          is_vshow:true,
        });
        console.log(this.data.is_vshow);
        this.isNoPlay();
        break;
      case 1:
        if (audition == 1) {
          this.setData({
            is_update: false,
            is_buy: false,
            isLook: true,
            is_vshow: true,
            is_show: false,
          });
          this.videoPlay(index, address, course_id, id, coverSrc);
          // this.getHistory(course_id,id); //试看状态不执行记忆播放
          break;
        } else if (audition == 0) {
          console.log('333333走了这个逻辑吗');
          this.isNoPlay();
          break;
        } else {
          break;
        }
        case 2:
          this.setData({
            is_update: false,
            is_buy: false,
            isLook: true,
          });
          this.videoPlay(index, address, course_id, id, coverSrc);
          this.getHistory(course_id,id); //试看状态不执行记忆播放
          break;
        case 3:
        case 4:
          this.setData({
            is_update: false,
            is_buy: false,
            isLook: true,
          });
          this.videoPlay(index, address, course_id, id, coverSrc);
          this.getHistory(course_id,id); //试看状态不执行记忆播放
          break;
        default:
          break;
    }
  },
  setHistory(course_id, id) {
    app._getNetWork({
      url: app.getNetAddresss("plugin.video-demand.api.video-demand-member.set-watch-history"),
      data: {
        course_id: course_id,
        chapter_id: id,
        history_time:parseInt(this.data.viewingDuration)
      },
      success:(res) =>  {
        
      },  
    });
  },
  getHistory(course_id, id) {
    app._getNetWork({
      url: app.getNetAddresss("plugin.video-demand.api.video-demand-member.get-watch-history"),
      data: {
        course_id: course_id,
        chapter_id: id,
      },
      success:(res) =>  {
        let resData = res.data;
        if (res.data.result == 1) {
          let data = resData.data;
          this.setData({
            timingTime:data.history_time,
            viewingDuration:data.history_time,
          })
          if(!this.data.videoEventDom) { //切换视频章节
            this.data.videoEventDom = wx.createVideoContext('polyvLiveVideo', this);
            this.data.videoEventDom.seek(Number(data.history_time));
            this.data.videoEventDom.play();
          } else {
            this.data.videoEventDom.seek(Number(data.history_time));
            this.data.videoEventDom.play();
          }
          wx.hideLoading();
        } else {
          //没有观看历史的情况
          if(!this.data.videoEventDom) { //自动播放情况
            this.data.videoEventDom = wx.createVideoContext('polyvLiveVideo', this);
            this.data.videoEventDom.seek(0);
            wx.hideLoading();
            this.data.videoEventDom.play();
          } else {
            this.data.videoEventDom.seek(0);
            wx.hideLoading();
            this.data.videoEventDom.play();
          }
          console.log(this.data.videoEventDom.play());
        }
      },  
    });
  },
  isNoPlay() {
    this.setData({
      is_update: true,
      is_buy: true,
      isLook: false,
    });
    if (!this.data.styleSetOptions.buy_now_button) return;
    this.openBuyDialog();
  },
  openBuyDialog() {
    if(this.data.buy_course){
      return;
    }
    if (this.data.is_try_time) {
      clearTimeout(this.data.is_try_time);
      this.data.is_try_time = null;
    }
    Dialog.alert({
      title: "提示",
      message:this.data.goodsInfo?.tip_msg ||  `请升级会员或者购买${this.data.course_name}`,
      context: this,
    }).then(() => {
      // on close
    });
  },
  videoPlayInit(event){
    wx.hideLoading();
    if(this.data.duration_log_flag){
      this.duration_log();
    }
    if(this.data.flag){
      this.data.flag = false;
      if(this.data.timer_study) clearInterval(this.data.timer_study)
      this.data.timer_study =  setInterval(()=>{
          this.data.current_time++;
          if(this.data.current_time / 60 == this.data.current_min){
            this.data.current_min++;
            this.study_duration()
          }
      },1000)
    }
  },
  videoEndInit(){
    clearInterval(this.data.timer_study);
    this.data.timer_study  = null;
    this.data.duration_log_flag = true;
    this.data.flag = true;
    this.data.current_time = 1;
    this.data.current_min = 1;

    //新增的功能
    this.setData({
      viewingDuration:0
    })
    if(this.data.video_courses[this.data.activeNames].has_many_chapter.length > 0) {
      let chapterItem = this.data.video_courses[this.data.activeNames ].has_many_chapter.find((chapterItem) => chapterItem.id == Number(this.data.chapter_id));
      let chapterIndex =  this.data.video_courses[this.data.activeNames].has_many_chapter.findIndex((chapterItem) => chapterItem.id == Number(this.data.chapter_id));
      if(chapterIndex != -1) {
        let nextChapter = this.data.video_courses[this.data.activeNames].has_many_chapter[chapterIndex + 1];
        if(nextChapter) { //自动播放下一个章节
          this.viewPermission(nextChapter.id, chapterIndex+ 1, nextChapter.course_id, nextChapter.is_audition, this.activeNames);
          this.setHistory(chapterItem.course_id,chapterItem.id);
          
        } else {
          if(this.data.video_courses[this.data.activeNames+ 1]) {
            let currentChapter =  this.data.video_courses[this.data.activeNames + 1].has_many_chapter[0];
            this.setData({
              activeNames:this.data.activeNames+1
            })
            if(currentChapter) {
              this.viewPermission(currentChapter.id, 0, currentChapter.course_id, currentChapter.is_audition, this.data.activeNames);
              // this.setHistory(currentChapter.course_id,currentChapter.id); //不清除下一个章节的播放记录
            }
          }
           //避免查询最后一个视频的时候没有清除当前时间记录
           this.setHistory(chapterItem.course_id,chapterItem.id);
        }
        
      } else {
        if(chapterItem) {
          this.setHistory(chapterItem.course_id,chapterItem.id);
        }
        
      }
    }
  },
  videoPauseInit(){
    clearInterval(this.data.timer_study);
    this.data.timer_study  = null;
    this.data.flag = true;
    this.data.duration_log_flag = false;
  },
  duration_log(){
    let arr =this.data.chapterdigList[this.data.activeNames];
    let _result =arr.has_many_chapter.filter(item=>item.id==this.data.active);
    let json_2 = {
      course_id:this.data.courseId,
      chapter_id:this.data.chapter_id,
      course_name:this.data.goodsInfo.goods_title,
      chapter_name:arr.chapter_name,
      nodule_name:_result[0]?.chapter_name
    }
    app._postNetWork({
      url:app.getNetAddresss('plugin.video-demand.api.views.view-log'),
      data:json_2,
      success:res=>{
        console.log(res,"res===")
      }
    })

  },
  study_duration(){
    let json = {
      course_id:this.data.courseId,
      chapter_id:this.data.chapter_id,
      goods_id:this.data.goods_id,
      relation_order_id:this.data.relation_order_id
    };
    app._postNetWork({
      url:app.getNetAddresss('plugin.video-demand.api.views.study-duration-log'),
      data:json,
      success:res=>{
        console.log(res,"res===")
      }
    })
  },
  videoTimeupdate(event) {
    let currentTime = Math.ceil(event.detail.currentTime);
    
    if (Number(this.freeTime) > -1 && parseInt(event.detail.currentTime) == this.freeTime) {
      this.setData({
        islive: false,
        is_show: true,
        is_vshow: false
      });
      this.isNoPlay();
      //可以看
    }
    if (Number(this.freeTime) > -1 && event.detail.currentTime > this.freeTime) {
      wx.showToast({
        title: `试看时长为${this.freeTime}秒`,
        icon: "none",
        duration: 1500,
      });
      this.data.videoEventDom.seek(Number(this.freeTime) - 2);
    }
    if(currentTime + 10 < this.data.timingTime) { //避免拖拽进度条计算不到倒计时请求接口
      this.data.timingTime = currentTime + 10;
      console.log(this.data.timingTime)
      // this.setHistory(this.data.courseId,this.data.chapter_id);
    }
    if (currentTime + 1 > this.data.timingTime) {
      this.data.timingTime = Math.ceil(event.detail.currentTime) + 10; //处理拖拽进度条播放事件
      this.setHistory(this.data.courseId,this.data.chapter_id);
    }
    this.setData({
      viewingDuration: currentTime
    })
  },
  //进入视频检测
  videoMinView(event) {
    console.log(event);
  },
  outVideoView(event) {
    this.setHistory(this.data.courseId,this.data.chapter_id)
    console.log('视频退出视频退出')
  },
  // 观看视频
  videoPlay(index, src, course_id, id, coverSrc) {
    wx.showLoading({
      title: '视频缓存中...',
    });
    if(src == this.data.vedioSrc) { //相同的视频链接不会触发视频加载事件
      console.log('322322222');
      wx.hideLoading();
    }
    this.setData({
      is_show: false,
      is_vshow: true,
      active: id,
      vedioSrc: src,
      poster:'',
      coverImg: coverSrc,
    });
    
    // 判断当前路径
    this.isMp4(this.data.vedioSrc);
    
    //设置观看时间记录
    // this.setHistory(course_id,id);
    console.log('视频缓存中******');
  },
  // 判断是否MP4
  isMp4(src) {
    if (src == "") return;
    if (src.endsWith(".mp4") || src.endsWith(".MP4") || src.endsWith(".m3u8")) {
      this.setData({
        isVideo: true,
        is_show: false,
      });
    } else {
      this.setData({
        isVideo: false,
        is_show: false,
      });
    }
  },
  study() {
    this.setData({
      is_show: false,
      is_vshow: true,
    });
  },
  // 升级会员
  update() {
    if (this.data.ios_virtual_pay) {
      wx.showModal({
        title: "提示",
        content: "十分抱歉，由于相关规定，你暂时无法在这里充值！",
        confirmText: "知道了",
        showCancel: false,
        success(res) {
          if (res.confirm) {
            console.log(res);
          }
        },
      });
      return false;
    }
    wx.navigateTo({
      url: "/packageA/member/course/CourseMemberUpdate/CourseMemberUpdate?goods_id=" + this.data.goods_id,
    });
  },
  // 立即购买
  buy() {
    if (this.data.HasBuyPermissions) {
      wx.showModal({
        title: "提示",
        content: this.data.HasBuyPermissions,
        confirmText: "确定",
        showCancel: false,
        success(res) {},
      });
      return false;
    }
    if (this.data.ios_virtual_pay) {
      wx.showModal({
        title: "提示",
        content: "十分抱歉，由于相关规定，你暂时无法在这里充值！",
        confirmText: "知道了",
        showCancel: false,
        success(res) {
          if (res.confirm) {
            console.log(res);
          }
        },
      });
      return false;
    }
    //价格权限
    if (this.data.vip_level_status && this.data.vip_level_status.status == 1) {
      wx.showToast({
        title: this.data.vip_level_status.tips,
        icon: "none",
        duration: 1500,
      });
      return false;
    }

    wx.navigateTo({
      url: "/packageD/buy/myOrder_v2/myOrder_v2?tag=-2&total=1&optionsId=&goodsId=" + this.data.goods_id,
    });
  },
  // 跳转至我的课程
  toMyCourse() {
    wx.navigateTo({
      url: "/packageA/member/course/CourseMy/CourseMy",
    });
  },
  toHome() {
    if(this.data.goodsInfo.has_one_goods?.plugin_id == 92 && this.data.goodsInfo.shop_id) {
      wx.navigateTo({
        url: "/packageA/member/supplier/SupplierShop/SupplierShop?id=" + this.data.goodsInfo.shop_id
      });
      return;
    }
    wx.navigateTo({
      url: "/packageG/index/index",
    });
  },
  // 推荐商品跳转
  pushGoodGoto(val) {
    let item = val.currentTarget.dataset.item;
    wx.navigateTo({
      url: "/packageA/detail_v2/detail_v2?id=" + item.id,
    });
  },
  // 选择打赏金额
  chooseMoney(e) {
    let money = e.currentTarget.dataset.money;
    this.setData({
      rewardMoney: money,
    });
  },
  moneyInput(e) {
    this.setData({
      rewardMoney: e.detail,
    });
  },
  // 确定打赏
  confirmReward() {
    if (app._isTextEmpty(this.data.rewardMoney)) {
      wx.showToast({
        title: "请输入或选择打赏金额",
        icon: "none",
        duration: 1500,
      });
      return;
    }

    if (this.data.rewardMoney <= 0) {
      wx.showToast({
        title: "打赏金额必须大于0",
        icon: "none",
        duration: 1500,
      });
      return;
    }

    this.getPayData();
  },
  // 获取支付类型参数
  getPayData() {
    var that = this;
    app._getNetWork({
      url: app.getNetAddresss("plugin.video-demand.api.lecturer-reward.pay-type"),
      success: function (res) {
        if (res.data.result === 1) {
          let btnData = res.data.data.buttons;
          that.setData({
            showPopup: false,
            btnData: btnData,
            rewardPayshow: true,
          });
        } else {
          console.error(res);
        }
      },
      fail: function (res) {
        console.error(res);
      },
    });
  },
  // 支付
  payPost(e) {
    this.setData({
      rewardPayshow: false,
    });
    let type, name, btn = null;
    if (e.currentTarget) {
      type = e.currentTarget.dataset.info.value;
      name = e.currentTarget.dataset.info.name;
      btn = e.currentTarget.dataset.info;
    } else {
      type = e.value;
      name = e.name;
      btn = e;
    }
    let dataJson = {
      pay_method: type,
      amount: this.data.rewardMoney,
      pay_name: name,
      goods_id: this.data.goods_id,
      trick_id: this.data.stickid,
      client_type: "2",
    };

    app._getNetWork({
      url: app.getNetAddresss("plugin.video-demand.api.lecturer-reward.run-reward-pay"),
      data: dataJson,
      success: (res) => {
        if (res.data.result === 1) {
          this.handleOtherPay(btn, type, res.data.data);
          this.onClose();
        } else {
          Dialog.alert({
            title: "提示",
            message: res.data.msg,
            context: this,
          }).then(() => {
            // on close
          });
        }
      },
      fail: (res) => {
        console.error(res);
      },
    });
  },
  moneyShow() {
    this.setData({
      showPopup: true,
    });
  },
  openInputReward() {
    this.setData({
      showPopup: false,
      rewardMoneyBtn: true,
    });
  },
  onClose() {
    this.setData({
      showPopup: false,
      rewardMoneyBtn: false,
      actionSheetShow: false,
      questionnaire_is_open: false,
    });
  },
  openActionSheet() {
    this.setData({
      showPopup: false,
      actionSheetShow: true,
    });
  },
  previewImage: function (e) {
    var current = e.target.dataset.src; // 这里获取到的是一张本地的图片
    wx.previewImage({
      current: current, // 需要预览的图片链接列表
      urls: [current], // 当前显示图片的链接
    });
  },
  // 足迹记录
  footSet() {
    if (!this.data.isGoods) {
      return;
    }
    let urlStr = app.getNetAddresss("member.member-history.store");
    urlStr += "&goods_id=" + this.properties.goodsId + "&mark=" + this.properties.mark + "&mark_id=" + this.properties.mark_id;
    app._getNetWork({
      showToastIn: false,
      url: urlStr,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          console.log(res);
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
      fail: function (res) {},
    });
  },
  onChange(event) {
    this.data.current_time = 0;
    clearInterval(this.data.timer_study);
    this.data.timer_study  = null;
    this.data.duration_log_flag = true;
    console.log(event,"event===")
    this.setData({
      activeNames: event.detail,
    });
  },
  rewardPayshowClose() {
    this.setData({
      rewardPayshow: false,
    });
  },
  rewardPayCancelBtn() {
    this.setData({
      rewardPayshow: false,
    });
  },
  onChangecountDown(e) {
    this.setData({
      timeData: e.detail,
    });
  },
  countDownFinish() {
    this.setData({
      iscCountDownFinish: true
    });
  },
  // 去加群
  toGroupCode() {
    if (this.data.goods_plugin.group_code.jump_mode === 'home') {
      wx.reLaunch({
        url: '/packageE/groupCode/groupCode',
      });
    } else if (this.data.goods_plugin.group_code.code_mini_url) {
      wx.navigateTo({
        url: this.data.goods_plugin.group_code.code_mini_url
      });
    }
  },
  // 广告语跳转
  toAdvertising() {
    wx.navigateTo({
      url: this.data.advertising.min_link
    });
  },
  getVideoCourse(page = 1) {
    app._getNetWork({
      url: app.getNetAddresss("plugin.video-demand.api.video-course-goods.get-dig-chapter"),
      data: {
        page,
        course_id: this.data.course_id
      },
      success: resdata => {
        let {
          result,
          msg,
          data
        } = resdata.data;
        if (result !== 1) {
          return app.tips(msg);
        }
        this.setData({
          page: data.current_page,
          total_page: data.last_page
        })
        if (page == 1) {
          this.setData({
            video_courses: data.data
          })
        } else {
          let video_courses = this.data.video_courses.concat(data.data);
          this.setData({
            video_courses
          })
        }
      },
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
   
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    clearInterval(this.data.timer_study);
    this.data.timer_study  = null;
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    clearInterval(this.data.timer_study);
    this.data.timer_study  = null;
    if(this.data.videoEventDom) {
      this.data.videoEventDom.exitPictureInPicture();
      
    }
    this.setHistory(this.data.courseId,this.data.chapter_id)
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    var value = wx.getStorageSync("yz_uid");
    var path = "";
    if (value) {
      path = value;
    }

    let _title = app._isTextEmpty(this.data.courseShare.share_title) ? this.data.goodTit : this.data.courseShare.share_title;

    // let _link = "/packageA/detail_v2/detail_v2?id=" + this.data.chapter_id + "&chapter_id="+this.data.chapter_id +"&courseId=" + this.data.courseId+'goods_id='+this.data.goods_id + "&mid=" + path;

    let _link = `/mircoApp/videoOnDemand/index/index?chapter_id=${this.data.chapter_id}&courseId=${this.data.courseId}&goods_id=${this.data.goods_id}&mid=${path}&index=${this.data.activeNames}`;

    let _imgUrl = app._isTextEmpty(this.data.courseShare.share_thumb) ? this.data.courseData.has_one_goods.thumb : this.data.courseShare.share_thumb;

    let _desc = this.data.courseShare.share_desc;
    console.log(_link,"_link-====--====")
    return {
      title: _title,
      desc: _desc,
      imageUrl: _imgUrl,
      path: _link
    };
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    console.log(this.data.page >= this.data.total_page,"this.data.page >= this.data.total_page")
    if (this.data.page >= this.data.total_page) {
      return;
    }
    let page = this.data.page + 1;
    this.getVideoCourse(page);
  }
})